package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private UserFeign userFeign;

    /**
     * 查看更多回复内容
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //初始化数据
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //查看mongo中有无当前评论
        Query query = Query.query(Criteria
                .where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null || Collections.isEmpty(apCommentRepays)) {
            return ResponseResult.okResult(apCommentRepays);
        }
        //如果登录并且查询的集合不为空 则获取自己点过赞的回复
        Integer uid = user.getId();
        List<String> apCommentIds = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query likeQuery = Query.query(Criteria
                .where("authorId").is(uid)
                .and("commentRepayId").in(apCommentIds));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(likeQuery, ApCommentRepayLike.class);
        if (Collections.isEmpty(apCommentRepayLikes) || apCommentRepayLikes.size() < 1) {
            return ResponseResult.okResult(apCommentRepays);
        }
        List<String> apCommentRepayLikeIds = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());
        //处理交集
        ArrayList<ApCommentRepayVo> apCommentRepayVos = new ArrayList<>();
        apCommentRepays.forEach(apCommentRepay -> {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay,apCommentRepayVo);
            if (apCommentRepayLikeIds.contains(apCommentRepay.getId())) {
                apCommentRepayVo.setOperation((short) 0);
            }
            apCommentRepayVos.add(apCommentRepayVo);
        });
        return ResponseResult.okResult(apCommentRepayVos);
    }

    /**
     * 保存回复
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //获取当前登录的用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //安全过滤判断评论中是否含有敏感词
        Boolean aBoolean = commentService.sensitiveContentFilter(dto.getContent());
        if (!aBoolean) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前回复包含有敏感词！！！！");
        }
        //判断数据库中是否存在当前评论
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前评论不见了");
        }
        //保存评论回复的操作
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        BeanUtils.copyProperties(dto, apCommentRepay);
        //远程调用查询当前登录用户的信息
        ResponseResult<ApUser> responseResult = userFeign.findUserById(user.getId());
        if (responseResult.getCode() != 0) {
            log.error("userFeign 远程调用 findUserById 出错，错误原因：{}，参数：{}", responseResult.getErrorMessage(), user.getId());
            CustomException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApUser apUser = responseResult.getData();
        if (apUser == null) {
            log.error("当前登录用户信息有误，当前登录用户id:{}", user.getId());
        }
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.insert(apCommentRepay);
        //数据回显
        ApComment comment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        comment.setReply(comment.getReply() + 1);
        mongoTemplate.save(comment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复的评论
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //获取当前登录的状态
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustomException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据id查询别回复的评论
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前回复不存在哦");
        }
        //判断有没有点过赞
        Query query = Query.query(Criteria
                .where("commentRepayId").is(dto.getCommentRepayId())
                .and("authorId").is(user.getId()));
        Short operation = dto.getOperation();
        Integer uid = user.getId();
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (apCommentRepayLike != null && operation == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "你已经点过赞啦");
        }
        if (apCommentRepayLike == null && operation == 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "你还没有点赞呢");
        }
        //保存点赞行为
        if (operation == 0) {
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(uid);
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);
            //更新点赞次数
            commentRepay.setLikes(commentRepay.getLikes() + 1);
        } else {
            mongoTemplate.remove(query, ApCommentRepayLike.class);
            //更新点赞次数
            commentRepay.setLikes(commentRepay.getLikes() - 1);
        }
        mongoTemplate.save(commentRepay);
        //数据返回
        HashMap<String, Integer> map = new HashMap<>();
        map.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
